"""ComBat

.. helpdoc::
Performs comBat adjustment of array data to compensate for batch effects.  This widget will accept either two data tables representing the normalized expression values and the batch designations or a combination of file names representing the same.
"""

"""<widgetXML>
    <name>ComBat</name>
    <icon>Default.png</icon>
    <tags> 
        <tag>Microarray</tag> 
    </tags>
    <summary>Performs comBat adjustment of array data to compensate for batch effects.  This widget will accept either two data tables representing the normalized expression values and the batch designations or a combination of file names representing the same.</summary>
    <details>Performs comBat adjustment of array data to compensate for batch effects.  This widget will accept either two data tables representing the normalized expression values and the batch designations or a combination of file names representing the same.</details>
    <author>
        <authorname>Kyle R Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""



"""
<name>ComBat</name>
<description>Performs comBat adjustment of array data to compensate for batch effects.  This widget will accept either two data tables representing the normalized expression values and the batch designations or a combination of file names representing the same.</description>
<tags>Microarray</tags>
"""

from OWRpy import *
#import OWGUI
import redRGUI, os
import globalData
import libraries.base.signalClasses as signals
import libraries.affy.signalClasses.RAffyBatch as rab
from libraries.base.qtWidgets.fileNamesComboBox import fileNamesComboBox as redRFileNamesComboBox
from libraries.base.qtWidgets.groupBox import groupBox as redRGroupBox

class comBat(OWRpy):
    globalSettingsList = ['filecombo', 'recentFiles','path']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.path = os.path.abspath('/')
        self.methodcombo = 0
        self.saveSettingsList.extend(['recentFiles', 'path', 'methodcombo'])
        #set R variable names
        self.setRvariableNames(['affyBatch','folder', 'cm'])
        #signals
        
        """.. rrsignals::"""
        self.inputs.addInput('affyBatch', 'Normalized Expression Values', signals.RDataFrame.RDataFrame, self.processData)
        
        """.. rrsignals::"""
        self.inputs.addInput('batchGroupings', 'Batch Identification Table', signals.RDataFrame.RDataFrame, self.processBatches)
        
        """.. rrsignals::"""
        self.outputs.addOutput("normBatch", "Batch Normalized Expression Values", signals.RDataFrame.RDataFrame)
        
        #GUI
        box = redRGroupBox(self.controlArea, "Select Expression Data",orientation='horizontal')
        #sizePolicy=QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed))
        box2 = redRGroupBox(self.controlArea, "Select Identification Data", orientation = 'horizontal')
        self.filecomboData = redRFileNamesComboBox(box, label = 'Expression Data', toolTip = 'Set to a comma delimited file representing the expression data')
        
        
        """.. rrgui::"""
        self.filecomboIdentData = redRFileNamesComboBox(box2, label = 'Identification Data', toolTip = 'Set to a tab delimited file representing the batch designations')
        #self.filecombo.setCurrentIndex(0)
        
        """.. rrgui::"""
        button = redRButton(box, 'Browse', callback = self.browseFile)
        
        """.. rrgui::"""
        button2 = redRButton(box2, 'Browse', callback = self.browseIdentData)
        
        """.. rrgui::"""
        self.numArrays = redRRadioButtons(self.controlArea, label = 'Number of arrays', 
        buttons = ['Less than 40', 'More than 40'],setChecked='Less than 40', orientation='horizontal')

        """.. rrgui::"""
        button2 = redRCommitButton(self.bottomAreaRight, 'Process Folder', callback = self.process)
        
    def browseFile(self): 
        fn = QFileDialog.getExistingDirectory(self, "Directory", self.path)
        
        #print unicode(fn)
        if fn.isEmpty(): return
        self.filecomboData.addFile(unicode(fn))
        self.saveGlobalSettings()
    def browseIdentData(self):
        fn = QFileDialog.getExistingDirectory(self, "Directory", self.path)
        
        #print unicode(fn)
        if fn.isEmpty(): return
        self.filecomboIdentData.addFile(unicode(fn))
        self.saveGlobalSettings()
    def process(self):
        dir = self.filecombo.getCurrentFile()
        if not dir:
            return
        self.status.setText("Your data is processing")
        #required librarys
        if not self.require_librarys(['affy']):
            self.status.setText('R Libraries Not Loaded.')
            return
        if self.numArrays.getChecked() == 'Less than 40':
            self.R(self.Rvariables['affyBatch']+'<-ReadAffy(celfile.path="'+dir+'")','setRData',True)
            self.status.setText("Your data has been processed with ReadAffy.")
        else:
            self.status.setText("This may take several minutes")
            self.R(self.Rvariables['affyBatch']+'<-justRMA(celfile.path='+self.Rvariables['folder']+')','setRData',True)
            self.status.setText("Data preprocessed with justRMA.")
        self.R(self.Rvariables['cm']+'<-list()') # in this case the cm should be the colnames, not the rownames as is usual
        self.sendMe()
        
    
    def sendMe(self):
        chipType = self.R('annotation('+self.Rvariables['affyBatch']+')')
        globalData.setGlobalData(self,'chipType',chipType,description='Chip Type')
        out2 = rab.RAffyBatch(data = unicode(self.Rvariables['affyBatch']))
        self.rSend("affyBatch", out2)
